<template>
  <div class='visual-methods pr'>
    <div class="upload-file">
      <span v-for="(item, index) in tabsData" :class="{'is-active':item.isActive}" :key="index" @click="item.click();changeActive(index)">{{item.label}}</span>
      <input type="file" ref="file_upload" @change="previewFile" accept="text/javascript,application/javascript">
    </div>
    <ul class="explain-list">
      <li v-for="(item, index) in myMethods" :key="index" :class="{'is-selected':false,pr:true}" @click="setSelected(item)" :title="item.explain||'暂无'">
        <p>{{item.method}}</p>
        <div>
          <i v-if="selected.includes(item.id)" class="el-icon-success color-green fr"></i>
          <i class="el-icon-error color-red fr" title="直接删除该项~" @click.stop="del(item)" ></i>
        </div>
      </li>
    </ul>
    <audio :src="voices.notice.sound" v-if="voices.notice.show" autoplay></audio>
  </div>
</template>
<script>
export default {
  components: {},
  name: "",
  data() {
    return {
      myMethods:[],
      maxlength:100,//最多保存的方法个数
      selected:[],//选中需要到处的方法
      noticeInfo:{//提示信息
        show:false,
        info:"",
        time:"7",//连续7天不使用就会提示信息
      },
      voices:{
        notice:{
          show:false,
          sound:require("./audios/notice.wav")
        }
      },
      tabsData:[
        {label:"方法仓库",isActive:true,click:this.getWarehouse},
        {label:"我的方法",isActive:false,click:this.upload},
        {label:"导出",isActive:false,click:this.download},
      ]
    };
  },
  methods: {
    upload(){
      this.$refs.file_upload.click()
    },

    /**
     * @name 获取仓库里面的方法
     */
    getWarehouse(){
      _g.apiPost("visualization/methods/list").then(res=>{
        this.getMethods({methods:res.methods,explains:res.explains})
      })
    },

    changeActive(index){
      this.tabsData.forEach((ele,eleIndex)=>{
        this.$set(ele,"isActive",index===eleIndex)
      })
    },

    /**
     * @name 选中方法并且导出--就是下载文件
     */
    download(){
      var content=""
      this.myMethods.forEach(ele=>{
        if(this.selected.includes(ele.id)){
          content+=(ele.explain.slice(0,-2).replace(/\*\s/g,"\n *")+`\n */`||"")+"\n"+ele.method.replace(/;/g,";\n")+", \n"
        }
      })
      content=`var globalFunctions = { \n` + content + '\n  } \n export default globalFunctions'
      this.doDownloadFile(content,"globalFunctions.js")
      this.selected=[]
    },

    /**
     * @name 下载选中内容
     */
    doDownloadFile(content,filename){
      var eleLink = document.createElement('a');
      eleLink.download = filename;
      eleLink.style.display = 'none';    // 字符内容转变成blob地址
      var blob = new Blob([content]);
      eleLink.href = URL.createObjectURL(blob);    // 触发点击
      document.body.appendChild(eleLink);
      eleLink.click();    // 然后移除
      document.body.removeChild(eleLink);
    },

    /**
     * @name 选中文件上传
     */
    previewFile(){
      var that=this
      var file = document.querySelector("input[type=file]").files[0];
      var reader = new FileReader();
      reader.onloadend=function(){
        // 得到functions
        var methods = this.result.replace(/\s{2,}/g,"").replace(/\/\*.{10,}?\//g,"").match(/{.*}/g)[0].slice(1,-1).split(/\B,\b(?!\d)/g)
        // 得到注释
        var explains=this.result.replace(/\s{2,}/g,"").match(/\/\*.{10,}?\//g);

        that.getMethods({methods,explains})

      }
      if(file)reader.readAsText(file);
    },

    /**
     * @name 获取方法数组
     * @params {obj} methods:方法数组；explains：方法注释数组
     */
    getMethods(obj={methods:[],explains:[]}){
      var results=[]
      var time = new Date().getTime()

      for(var index in obj.methods){
        // 方法去重
        if(this.myMethods.findIndex(val=>val.method==obj.methods[index])<0){
          results.push({
            id:time+index,
            explain:obj.explains[index],
            method:obj.methods[index]
          })
        }
      }

      var [...goals]=new Set([...results,...this.myMethods])
      if(goals.length>this.maxlength){
        alert(`最多只能保存${this.maxlength}条数据！`)
      }
      localStorage.setItem(localSaved.savedMethods,JSON.stringify({time,methods:goals.slice(0,this.maxlength)}))
      this.$set(this,"myMethods",goals)
    },

    /**
     * @name 获取本地保存的方法
     */
    getSavedMthods(){
      const savedData=JSON.parse(localStorage.getItem(localSaved.savedMethods))||{}
      var oldtime=savedData.time
      var oldmethods=savedData.methods||[]
      if(new Date().getTime()-oldtime>7*24*3600*1000)this.showNoticeInfo()
      this.$set(this,"myMethods",oldmethods)
    },

    /**
     * @name 显示提示信息
     */
    showNoticeInfo(){
      this.voices.notice.show=true
      setTimeout(()=>{
        this.voices.notice.show=false
      },2000)
    },


    /**
     * @name 设置选中
     */
    setSelected(item){
      this.selected.includes(item.id)?this.selected.splice(this.selected.indexOf(item.id),1):this.selected.push(item.id)
    },

    /**
     * @name 删除对应
     */
    del(item){
      // 删除视图
      const savedData=this.myMethods
      savedData.splice(savedData.findIndex(val=>val.id==item.id),1);

      // 删除保存
      const savedData1=JSON.parse(localStorage.getItem(localSaved.savedMethods))
      savedData1.methods.splice(savedData1.methods.findIndex(val=>val.id==item.id),1);
      localStorage.setItem(localSaved.savedMethods,JSON.stringify(savedData1))
    },

  },
  filters:{
    formaltExplain(val){
      return val
    }
  },
  created() {
    // localStorage.removeItem(localSaved.savedMethods)
    this.getSavedMthods()
  }
};
</script>
<style lang="scss" scoped>
.visual-methods {
  overflow-x: hidden;
  .upload-file{
    
    span{
      display: inline-block;
      width: 100px;
      height: 40px;
      color: #fff;
      background-color: #000;
      text-align: center;
      line-height: 40px;
      box-shadow: 1px -2px 10px 1px #000;
      transition: all .6s;
      margin-right: 20px;
      cursor: pointer;
    }

    span:hover,span.is-active{
      box-shadow: 2px 0px 10px 3px #000;
    }

    input{
      visibility: hidden;
      position: absolute;
      z-index: -1;
    }
  }

  .explain-list{
    padding: 10px;
    transform-style: preserve-3d;
    perspective: 5000px;

    li{
      margin-top: 10px;
      padding: 10px;
      overflow-wrap: break-word;
      background-color: #ddd;
      border-radius: 5px;
      box-sizing: border-box;
      border: 1px solid transparent;
      box-shadow: 1px -1px 10px 1px #666;
      transition: all .5s;
      display: flex;
      >p{
        flex: 1;
        max-width: calc(100% - 60px);
      }
      >div{
        margin-left: auto;
      }
    }
    li.is-selected{
      border-color: $blue;
    }
    li:hover{
      cursor: pointer;
      box-shadow:1px -1px 10px 1px orange;
    }
    .el-icon-error{
      display: none;
      margin-right: 10px;
    }
    li:hover .el-icon-error{
      display: inline-block;
      
    }
  }
  
}
</style>